from WindPy import w
w.start()
import pandas as pd
import numpy as np
from pricer import pricer

class oneTest(object):
    bond_list=pd.read_csv('match.csv',index_col=0)
    r=0.055
    q=0
    @classmethod
    def matchCode(cls,bondCode):
        return cls.bond_list.loc[bondCode,'UNDERLYINGCODE']
    def __init__(self,code,startDate,endDate,nominal,K=None) -> None:
        super().__init__()
        self.startDate=startDate
        self.endDate=endDate
        self.nominal=nominal
        temp=w.wsd(code, "close", startDate, endDate)
        self.time=temp.Times
        self.price_list=temp.Data[0]
        if K is None:
            self.K=1
        else:
            self.K=K
        self.pct_change=w.wsd(code, "pct_chg", startDate, endDate, "").Data[0]
        stock_code=oneTest.matchCode(code)
        self.sigma_list=w.wsd(stock_code,"volatilityratio",startDate,endDate,"CalculationTime=60;AnnualCoefficient=252").Data[0]
        self.sigma_list=np.array(self.sigma_list)/100
        self.pct_change=np.array(self.pct_change)/100
        self.pct_change=np.nan_to_num(self.pct_change)
    def init_price(self):
        T=(self.time[-1]-self.time[0]).days/365
        price=pricer.callOption(self.price_list[0],self.K*self.price_list[0],self.sigma_list[0],T,oneTest.r,oneTest.q)/self.price_list[0]
        return self.nominal*price
    def deltaPNL(self):
        n=len(self.price_list)
        delta_cash=np.zeros(n)
        delta_pnl=np.zeros(n)
        option_pnl=np.zeros(n)
        prices=np.zeros(n)
        for i in range(n):
            T=(self.time[-1]-self.time[i]).days/365
            prices[i]=pricer.callOption(self.price_list[i],self.K*self.price_list[0],self.sigma_list[i],T,oneTest.r,oneTest.q)*self.nominal/self.price_list[0]
            delta_cash[i]=pricer.callDelta(self.price_list[i],self.K*self.price_list[0],self.sigma_list[i],T,oneTest.r,oneTest.q)*(self.nominal/self.price_list[0])*self.price_list[i]
        for i in range(1,n):
            delta_pnl[i]=delta_cash[i-1]*self.pct_change[i]
            option_pnl[i]=prices[i]-prices[i-1]
        return delta_cash,prices,delta_pnl,option_pnl

if __name__=="__main__":
    a=oneTest("110043.SH","2021/01/01","2021/12/01",10000)
    df=pd.DataFrame(columns=['time','price','sigma','option_price','delta_cash','option_pnl','delta_pnl'])
    deltas,prices,delta_pnl,option_pnl=a.deltaPNL()
    df['time']=a.time
    df['price']=a.price_list
    df['sigma']=a.sigma_list
    df['option_price']=prices
    df['delta_cash']=deltas
    df['option_pnl']=option_pnl
    df['delta_pnl']=delta_pnl
    df['error']=(delta_pnl-option_pnl)/10000
    pass

